package com.aios.service.impl;

import java.util.Calendar;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import com.aios.dao.SystemUserMapper;
import com.aios.dao.SystemUserPasswordMapper;
import com.aios.entity.SystemUser;
import com.aios.entity.SystemUserPassword;
import com.aios.entity.mapper.ExpirePassword;
import com.aios.entity.unit.StatusEnum;
import com.aios.service.ExistValidationEnum;
import com.aios.service.SystemUserService;
import com.aios.util.Pager;

@Service("systemUserService")
public class SystemUserServiceImpl extends AbstractListService implements
		SystemUserService {
	
	private List<ExpirePassword> sysUserPasswordList;
	private final static int MAX=5;
	private final static int MIN=1;
	private final static Byte EXPIRE_STATUS=3;
	private final static Byte ALERT_STATUS=2;
	private final static int EXPIRE_TARGET_DAY = 175;
	private final static int EXPIRE_DAY = 180;
	@Autowired 
	private EmailService emailService;

	@Autowired
	private SystemUserMapper systemUserMapper;
	
	@Autowired
	private SystemUserPasswordMapper systemUserPasswordMapper;

	@Override
	public List<SystemUser> findAll() {
		return systemUserMapper.findAllByStatus(StatusEnum.ACTIVE
				.getStatusValue());
	}

	@Override
	public List<SystemUser> findAllNotDisabled() {
		return findAll();
	}

	@Override
	public List<SystemUser> findAllDisabled() {
		return systemUserMapper.findAllByStatus(StatusEnum.DELETED
				.getStatusValue());
	}

	@Override
	public SystemUser findById(Integer id) {
		return systemUserMapper.selectByPrimaryKey(id);
	}

	@Override
	public int save(SystemUser entity) {
		return this.systemUserMapper.insertWithoutID(entity);
	}

	@Override
	public int save(SystemUser entity, Integer systemUserID) {
		saveAddSettings(entity, systemUserID);
		return this.systemUserMapper.insertWithoutID(entity);
	}

	@Override
	public int update(SystemUser entity) {
		return this.systemUserMapper.updateByPrimaryKeySelective(entity);
	}

	@Override
	public int update(SystemUser entity, Integer systemUserID) {
		saveEditSettings(entity, systemUserID);
		return this.systemUserMapper.updateByPrimaryKeySelective(entity);
	}

	@Override
	public int delete(SystemUser entity) {
		return this.delete(entity.getId());
	}

	@Override
	public int delete(Integer id) {
		return this.systemUserMapper.deleteByPrimaryKey(id);
	}

	@Override
	public SystemUser signIn(String email, String password) {

		List<SystemUser> list = systemUserMapper
				.findByEmailAndPasswordWithoutStatus(email, password);

		if (list == null) {
			// error
		} else if (list.size() == 0) {
			// user not found
		} else if (list.size() > 1) {
			// too many users
		} else {
			if (list.get(0).getStatus() == 0 || list.get(0).getStatus() == 2) {
				Calendar calendar = Calendar.getInstance();
				list.get(0).setLastLogin(calendar.getTime());

				return list.get(0);
			} else if (list.get(0).getStatus() == 3) {
				return list.get(0);
			} else {
				return null;

			}

		}

		return null;
	}

	public ExistValidationEnum emailExistValidation(String email) {
		List<SystemUser> list = systemUserMapper.findByEmailAddress(email);

		if (list == null || list.size() == 0) {
			return ExistValidationEnum.NOT_EXIST;
		} else if (list.size() == 1) {
			return ExistValidationEnum.EXIST;
		} else {
			return ExistValidationEnum.MULTIPLE_EXIST;
		}
	}
	
	@Override
	public ExistValidationEnum emailExistValidation(String email, Integer id) {
		List<SystemUser> list = systemUserMapper.findEmailNotWithId(email, id);

		if (list == null || list.size() == 0) {
			return ExistValidationEnum.NOT_EXIST;
		} else if (list.size() == 1) {
			return ExistValidationEnum.EXIST;
		} else {
			return ExistValidationEnum.MULTIPLE_EXIST;
		}
	}

	public SystemUser findSystemUserByEmail(String email) {

		List<SystemUser> list = systemUserMapper.findByEmailAddress(email);

		if (list == null || list.size() == 0) {
			return null;
		} else if (list.size() == 1) {
			return list.get(0);
		} else {
			// error
			return null;
		}
	}

	@Override
	public Pager viewPaginatedActiveList(Integer start, Integer size) {

		prepare(start, size);
		try {
			pager.setTotal(systemUserMapper.countAllByStatus(StatusEnum.ACTIVE
					.getStatusValue()));
			pager.setList(systemUserMapper.findListPaginated(
					StatusEnum.ACTIVE.getStatusValue(), start, size));
		} catch (Exception e) {
			// logger
			e.printStackTrace();
		}

		return pager;
	}

	@Override
	public int getCount() {
		return systemUserMapper.countAllByStatus(0);
	}

	@Override
	public SystemUser findLastLogin() {
		return systemUserMapper.findLastLogin();
	}

	@Override
	public int saveWithPasswordRecords(SystemUser systemUser, Integer userId) {
		int retVal=0;
		Calendar calendar = Calendar.getInstance();
		
		retVal=this.save(systemUser, userId);
		SystemUserPassword record = new SystemUserPassword();
		record.setSystemUserId(	systemUserMapper.findByEmailAddress(systemUser.getEmail()).get(0).getId());
		record.setPasswordChangeDate(calendar.getTime());
		
		saveAddSettings(record, userId);
		retVal=systemUserPasswordMapper.insertWithoutId(record);
		
		return retVal;
	}
	
	public List<ExpirePassword> getSysUserPasswordList() {
		return sysUserPasswordList;
	}

	public void setSysUserPasswordList(List<ExpirePassword> sysUserPasswordList) {
		this.sysUserPasswordList = sysUserPasswordList;
	}
	
	@Scheduled(cron = "0 0 0 * * ?")
	public void checkExpire() {
		sysUserPasswordList = systemUserPasswordMapper.findByExpireDate(EXPIRE_TARGET_DAY );
		if (sysUserPasswordList != null) {
			for (int i = 0; i < sysUserPasswordList.size(); i++) {
				int days = sysUserPasswordList.get(i).getNumberOfDays();
				days = EXPIRE_DAY - days;
				if (days == MAX) {
					System.out.println("Send Email");
					SystemUser su=new SystemUser();
					su=findById(sysUserPasswordList.get(i).getSystemUserId());
					String key = emailService.sendPasswordResetEmail(su.getEmail());
					if(key.startsWith("error")) {
						System.out.println("Error sending Email");
					} else {
						System.out.println("Email Sent");
					}
				} else if (days == MIN) {
					System.out.println("Send Alert");
					if(sysUserPasswordList.get(i).getSystemUserId() != null){
						systemUserMapper.updateStatusByPrimaryKey(sysUserPasswordList.get(i).getSystemUserId(),ALERT_STATUS);
						}
				} else {
					System.out.println("Disable Account");
					if(sysUserPasswordList.get(i).getSystemUserId() != null){
					systemUserMapper.updateStatusByPrimaryKey(sysUserPasswordList.get(i).getSystemUserId(),EXPIRE_STATUS);
					}
				}
			}
			System.out.println("");
		}

	}
	
}
